<template>
  <div class="my-orders-page">
    <HeaderNav v-if="!isAdmin" />
    <AdminHeaderNav v-if="isAdmin" />

    <div class="orders-container">
      <div class="page-header">
        <h2>我的订单</h2>
        <div class="header-tabs">
          <div 
            class="tab-item" 
            :class="{ active: currentTab === 'pending' }"
            @click="currentTab = 'pending'"
          >
            待支付
          </div>
          <div 
            class="tab-item" 
            :class="{ active: currentTab === 'expired' }"
            @click="currentTab = 'expired'"
          >
            已失效
          </div>
        </div>
      </div>

      <div class="orders-content" v-loading="loading">
        <!-- 订单列表 -->
        <div v-if="filteredOrders.length > 0" class="order-list">
          <div v-for="order in filteredOrders" :key="order.id" class="order-card">
            <!-- 订单头部 -->
            <div class="order-header">
              <div class="order-info">
                <span class="order-no">订单号：{{ order.orderId }}</span>
                <span class="order-time">{{ order.createTime }}</span>
              </div>
              <el-tag :type="getStatusType(order.status)" size="large">
                {{ getStatusText(order.status) }}
              </el-tag>
            </div>

            <!-- 订单商品列表 -->
            <div class="order-items">
              <div 
                v-for="(item, index) in order.detailOrders" 
                :key="index" 
                class="order-item"
              >
                <div class="item-info">
                  <div class="item-name">{{ item.itemName }}</div>
                  <div class="item-spec" v-if="item.spec">规格：{{ item.spec }}</div>
                </div>
                <div class="item-price">¥{{ item.price }}</div>
                <div class="item-quantity">x{{ item.num }}</div>
                <div class="item-subtotal">¥{{ (item.price * item.num).toFixed(2) }}</div>
              </div>
            </div>

            <!-- 订单底部 -->
            <div class="order-footer">
              <div class="order-total">
                <span class="total-label">订单总额：</span>
                <span class="total-amount">¥{{ order.amount }}</span>
              </div>
              <div class="order-actions">
                <el-button 
                  v-if="order.status === 0" 
                  type="danger" 
                  size="small"
                  @click="cancelOrder(order.id)"
                >
                  取消订单
                </el-button>
                <el-button 
                  v-if="order.status === 0" 
                  type="primary" 
                  size="small"
                  @click="goToPay(order.orderId, order.amount)"
                >
                  立即支付
                </el-button>
                <el-button 
                  v-if="order.status === 2" 
                  size="small"
                  @click="deleteOrder(order.id)"
                >
                  删除订单
                </el-button>
              </div>
            </div>
          </div>
        </div>

        <!-- 空状态 -->
        <div v-else class="empty-state">
          <el-icon class="empty-icon"><Document /></el-icon>
          <p>{{ currentTab === 'pending' ? '暂无待支付订单' : '暂无已失效订单' }}</p>
          <el-button type="primary" @click="goShopping">去逛逛</el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Document } from '@element-plus/icons-vue'
import HeaderNav from '../../components/layout/HeaderNav.vue'
import AdminHeaderNav from '../../components/layout/AdminHeaderNav.vue'
import { useUserStore } from '../../stores/user'
import { getAllPendingOrExpiredOrdersService } from '../../api/order'

const router = useRouter()
const userStore = useUserStore()

interface DetailOrder {
  orderId: string
  itemName: string
  num: number
  price: number
  spec: string
}

interface OrderItem {
  id: number
  orderId: string
  amount: number
  addressId: number
  status: number
  detailOrders: DetailOrder[]
  createTime: string
}

const loading = ref(false)
const orderList = ref<OrderItem[]>([])
const currentTab = ref<'pending' | 'expired'>('pending')

const isAdmin = computed(() => userStore.isAdmin)

// 过滤订单列表
const filteredOrders = computed(() => {
  if (currentTab.value === 'pending') {
    return orderList.value.filter(order => order.status === 0)
  } else {
    return orderList.value.filter(order => order.status === 2)
  }
})

// 获取订单状态文本
const getStatusText = (status: number): string => {
  const statusMap: Record<number, string> = {
    0: '待支付',
    1: '已支付',
    2: '已失效'
  }
  return statusMap[status] || '未知状态'
}

// 获取订单状态类型
const getStatusType = (status: number): string => {
  const typeMap: Record<number, string> = {
    0: 'warning',
    1: 'success',
    2: 'info'
  }
  return typeMap[status] || 'info'
}

// 加载订单列表
const loadOrders = async () => {
  loading.value = true
  try {
    const res: any = await getAllPendingOrExpiredOrdersService()
    if (res.code === 0) {
      orderList.value = res.data || []
    } else {
      ElMessage.error(res.message || '加载失败')
    }
  } catch (error) {
    console.error('加载订单失败:', error)
    ElMessage.error('加载失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

// 跳转到支付页面
const goToPay = (orderId: string, amount: number) => {
  router.push({
    path: '/payment',
    query: {
      orderId: orderId,
      amount: String(amount)
    }
  })
}

// 取消订单
const cancelOrder = async (orderId: number) => {
  try {
    await ElMessageBox.confirm(
      '确定要取消该订单吗？',
      '取消订单',
      {
        confirmButtonText: '确定',
        cancelButtonText: '返回',
        type: 'warning'
      }
    )
    
    // TODO: 调用取消订单接口
    console.log('取消订单 ID:', orderId)
    ElMessage.success('订单已取消')
    loadOrders()
  } catch (error) {
    // 用户取消操作
  }
}

// 删除订单
const deleteOrder = async (orderId: number) => {
  try {
    await ElMessageBox.confirm(
      '确定要删除该订单吗？',
      '删除订单',
      {
        confirmButtonText: '确定',
        cancelButtonText: '返回',
        type: 'warning'
      }
    )
    
    // TODO: 调用删除订单接口
    console.log('删除订单 ID:', orderId)
    ElMessage.success('订单已删除')
    loadOrders()
  } catch (error) {
    // 用户取消操作
  }
}

// 去购物
const goShopping = () => {
  router.push('/layout')
}

onMounted(() => {
  loadOrders()
})
</script>

<style scoped lang="scss">
.my-orders-page {
  min-height: 100vh;
  background: #f5f5f5;
}

.orders-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 2rem 1rem;
}

.page-header {
  background: white;
  padding: 1.5rem 2rem;
  border-radius: 8px;
  margin-bottom: 1.5rem;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);

  h2 {
    font-size: 1.5rem;
    color: #303133;
    margin: 0 0 1rem 0;
  }

  .header-tabs {
    display: flex;
    gap: 1rem;
    border-bottom: 2px solid #f0f0f0;

    .tab-item {
      padding: 0.75rem 1.5rem;
      cursor: pointer;
      color: #606266;
      font-size: 1rem;
      transition: all 0.3s;
      position: relative;

      &:hover {
        color: #409eff;
      }

      &.active {
        color: #409eff;
        font-weight: 500;

        &::after {
          content: '';
          position: absolute;
          bottom: -2px;
          left: 0;
          right: 0;
          height: 2px;
          background: #409eff;
        }
      }
    }
  }
}

.orders-content {
  min-height: 400px;
}

.order-list {
  display: flex;
  flex-direction: column;
  gap: 1rem;
}

.order-card {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  overflow: hidden;
  transition: transform 0.3s, box-shadow 0.3s;

  &:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 16px rgba(0, 0, 0, 0.15);
  }

  .order-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 1rem 1.5rem;
    background: #f8f9fa;
    border-bottom: 1px solid #eee;

    .order-info {
      display: flex;
      flex-direction: column;
      gap: 0.25rem;

      .order-no {
        color: #303133;
        font-size: 0.95rem;
        font-weight: 500;
      }

      .order-time {
        color: #909399;
        font-size: 0.85rem;
      }
    }
  }

  .order-items {
    padding: 1.5rem;
    border-bottom: 1px solid #f0f0f0;

    .order-item {
      display: grid;
      grid-template-columns: 2fr 120px 80px 120px;
      align-items: center;
      gap: 1rem;
      padding: 1rem 0;
      border-bottom: 1px dashed #f0f0f0;

      &:last-child {
        border-bottom: none;
        padding-bottom: 0;
      }

      &:first-child {
        padding-top: 0;
      }

      .item-info {
        .item-name {
          font-size: 1rem;
          color: #303133;
          margin-bottom: 0.5rem;
          font-weight: 500;
        }

        .item-spec {
          color: #909399;
          font-size: 0.85rem;
        }
      }

      .item-price {
        color: #606266;
        font-size: 0.95rem;
        text-align: center;
      }

      .item-quantity {
        color: #909399;
        font-size: 0.9rem;
        text-align: center;
      }

      .item-subtotal {
        color: #ff6b6b;
        font-size: 1rem;
        font-weight: 500;
        text-align: right;
      }
    }
  }

  .order-footer {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 1rem 1.5rem;
    background: #fafafa;

    .order-total {
      .total-label {
        color: #606266;
        font-size: 0.95rem;
      }

      .total-amount {
        color: #ff6b6b;
        font-size: 1.5rem;
        font-weight: bold;
        margin-left: 0.5rem;
      }
    }

    .order-actions {
      display: flex;
      gap: 0.5rem;
    }
  }
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 4rem 2rem;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);

  .empty-icon {
    font-size: 5rem;
    color: #dcdfe6;
    margin-bottom: 1rem;
  }

  p {
    color: #909399;
    font-size: 1rem;
    margin-bottom: 1.5rem;
  }
}

@media (max-width: 768px) {
  .orders-container {
    padding: 1rem;
  }

  .page-header {
    padding: 1rem;

    h2 {
      font-size: 1.2rem;
    }

    .header-tabs {
      .tab-item {
        padding: 0.5rem 1rem;
        font-size: 0.9rem;
      }
    }
  }

  .order-card {
    .order-header {
      flex-direction: column;
      align-items: flex-start;
      gap: 0.75rem;
    }

    .order-items {
      .order-item {
        grid-template-columns: 1fr;
        gap: 0.5rem;

        .item-price,
        .item-quantity,
        .item-subtotal {
          text-align: left;
        }
      }
    }

    .order-footer {
      flex-direction: column;
      align-items: flex-start;
      gap: 1rem;

      .order-actions {
        width: 100%;
        flex-direction: column;

        .el-button {
          width: 100%;
        }
      }
    }
  }
}
</style>
